package com.sita.tboard.ui.activity;

import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.sita.bike.R;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.support.LocationController;
import com.sita.bike.utils.BluetoothUtils;
import com.sita.bike.utils.FormatUtils;
import com.sita.bike.utils.LogUtils;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.ui.view.BigDial;
import com.sita.tboard.ui.view.SmallDial;


public class DashboardActivity extends ActivityBase implements LocationSource, AMapLocationListener,
        BluetoothUtils.BluetoothDataListener, BluetoothUtils.BluetoothServiceListener {

    private static final String TAG = DashboardActivity.class.getSimpleName();

    private MapView mapView;
    private AMap aMap;
    private BigDial mBigDial;
    private SmallDial mSmallDial;
    private ImageView mImgOverlay;
    private ImageView imgBack;
    private OnLocationChangedListener mListener;
    private boolean hasBluetoothDataReceived = false;


    public static float calculateScale(float bigDialHeight, float smallDialHeight) {
        float scale = 1.0f;
//        float screenWidth = GlobalContext.sScreenWidth > GlobalContext.sScreenHeight ? GlobalContext.sScreenWidth : GlobalContext.sScreenHeight;
//        float screenHeight = GlobalContext.sScreenWidth > GlobalContext.sScreenHeight ? GlobalContext.sScreenHeight : GlobalContext.sScreenWidth;
//
//        screenHeight = screenHeight;// - GlobalContext.getGlobalContext().getResources().getDimension(R.dimen.top_tool_bar_height);
//        float scaleWidth = screenWidth / (bigDialHeight / 5 + smallDialHeight); //80 = ( 820 -660 )/ 2
//        float scaleHeight = screenHeight / bigDialHeight;
//
//        LogUtils.i(TAG, "scaleW=" + scaleWidth + "scaleH=" + scaleHeight);
//
//        scale = scaleHeight < scaleWidth ? scaleHeight : scaleWidth;
        return scale;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tboard_activity_dashboard);
        mapView = (MapView) findViewById(R.id.map);
        mBigDial = (BigDial) findViewById(R.id.bigdial);
        mSmallDial = (SmallDial) findViewById(R.id.smalldial);
        mImgOverlay = (ImageView) findViewById(R.id.zhao);
        imgBack = (ImageView) findViewById(R.id.img_portrait);
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
            }
        });
        mapView.onCreate(savedInstanceState);
        initMap();
        initDashboardLayout();
        registerBlueTooth();
    }

    private void registerBlueTooth() {
        resetBluetoothData();
        BluetoothUtils.initBluetooth(this, this);
        BluetoothUtils.registerBluetoothData(this);
    }

    @Override
    public void onDataReceived(int speed, int rpm, int shift) {
        LogUtils.i(TAG, "onDataReceived speed:" + speed + ", rpm" + rpm);
        hasBluetoothDataReceived = true;
        setDataFromBluetooth(speed, rpm, shift);
    }

    @Override
    public void onDeviceConnected() {

    }

    @Override
    public void onDeviceDisconnected() {
        hasBluetoothDataReceived = false;
        resetBluetoothData();
    }

    @Override
    public void onDeviceConnectionFailed() {
        hasBluetoothDataReceived = false;
        resetBluetoothData();
    }

    private void resetBluetoothData() {
        setDataFromBluetooth(0, 0, 0);
    }

    private void setDataFromBluetooth(int speed, int rpm, int shift) {
        mBigDial.setAngle(speed);
        mSmallDial.setAngle(rpm);
    }

    protected void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    private void setUpMap() {
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(Constants.DEFAULT_LATLNG));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(19));
        aMap.setMapType(AMap.MAP_TYPE_NIGHT);//夜景地图模式
        CameraUpdate cameraupdate = CameraUpdateFactory.changeTilt(30);
        aMap.moveCamera(cameraupdate);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
        // 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
        aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
    }


    private void initDashboardLayout() {

        //大表盘位置
        mBigDial.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int bigDialHeight;
                int scrWidth;
                int screenWidth = GlobalContext.sScreenWidth;
                int screenHeight = GlobalContext.sScreenHeight;

                mBigDial.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                //现在布局全部完成，可以获取到任何View组件的宽度、高度、左边、右边等信息

                DisplayMetrics metric = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metric);
                scrWidth = metric.widthPixels;     // 屏幕宽度（像素）
                bigDialHeight = mBigDial.getMeasuredHeight();

                RelativeLayout.LayoutParams bigdialParams = (RelativeLayout.LayoutParams) mBigDial.getLayoutParams();

                bigdialParams.leftMargin = (scrWidth - bigDialHeight) / 2;
                mBigDial.setLayoutParams(bigdialParams);

                //设置地图宽度
                RelativeLayout.LayoutParams mapViewParams = (RelativeLayout.LayoutParams) mapView.getLayoutParams();
                mapViewParams.width = scrWidth / 3 + 20;
                mapViewParams.leftMargin = (scrWidth - bigDialHeight) / 2 - scrWidth / 3 + (bigDialHeight / 2 - scrWidth / 6) + 10;
                int h = (scrWidth - bigDialHeight) / 2 - scrWidth / 3 + (bigDialHeight / 2 - scrWidth / 6);
                mapView.setLayoutParams(mapViewParams);
                //设置遮罩宽度
                RelativeLayout.LayoutParams zhaoParams = (RelativeLayout.LayoutParams) mImgOverlay.getLayoutParams();
                zhaoParams.width = scrWidth / 3 + 20;
                zhaoParams.leftMargin = (scrWidth - bigDialHeight) / 2 - scrWidth / 3 + (bigDialHeight / 2 - scrWidth / 6) + 10;
                mImgOverlay.setLayoutParams(zhaoParams);

                //小表盘位置
                RelativeLayout.LayoutParams smalldialParams = (RelativeLayout.LayoutParams) mSmallDial.getLayoutParams();
                smalldialParams.leftMargin = scrWidth / 2 + bigDialHeight / 5;
                int h2 = (scrWidth - bigDialHeight) / 2 - bigDialHeight / 20;
                mSmallDial.setLayoutParams(smalldialParams);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }

    }

    @Override
    public void onPause() {
        if (mapView != null) {
            mapView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
        if (aMap != null) {
            aMap.setMyLocationEnabled(false);
        }

        BluetoothUtils.unregisterDataListener(this);
        BluetoothUtils.unregisterServiceListener(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }

    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                Log.d("amapLocation", amapLocation.toString());
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                float gpsSpeed = amapLocation.getSpeed(); // m/s
                if (!hasBluetoothDataReceived) {
                    mBigDial.setAngle(FormatUtils.convertSpeedToKMH(gpsSpeed));
                    mSmallDial.setAngle(0);
                }
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        LocationController.startTracking(this);
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        LocationController.stopTracking(this);
    }

    private void close() {
        this.finish();
    }
}
